import requests
import json      
import os
from openai import OpenAI
import re 
import qianfan
from volcengine.maas import MaasService, MaasException, ChatRole
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.hunyuan.v20230901 import hunyuan_client, models
from http import HTTPStatus
from dashscope import Generation

def llm_extract_resume(llm_type, prompt, resume_content):
    """
    调用合适的大模型来解析简历，返回标准的json格式简历数据
    
    :param llm_type: LLM类型
    :param prompt: 系统提示词
    :param resume_content: 需要解析的简历内容
    :return: response_json：解析后的结果
    """
    model_mapping = {
        "chatgpt": chatgpt_extract_resume,
        "wenxin": wenxin_extract_resume,
        "kimi": kimi_extract_resume,
        "huoshan": huoshan_extract_resume,
        "tencent": tencent_extract_resume,
        "qwen": qwen_extract_resume,
    }

    print(f"正在使用{llm_type}进行简历解析...")
    
    try:
        response_json = model_mapping[llm_type](prompt, resume_content)
    except KeyError:
        print(f"未知的LLM类型：{llm_type}")
        raise ValueError(f"不支持的LLM类型：{llm_type}")
    
    if response_json:
        try:  
            data = json.loads(response_json) 
            return data
        except json.JSONDecodeError as e:  
            print(f"简历 JSON解析错误: {e}")  
            return None
    
def chatgpt_extract_resume(prompt, resume_content):
    # 调用gptAPI，解析简历，输出为json格式
    os.environ["OPENAI_API_KEY"] = "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"

    client = OpenAI()
    client.api_key = os.environ["OPENAI_API_KEY"] 

    try:
        completion = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": prompt},
                {"role": "user", "content": resume_content}
            ]
        )
        response_json = completion.choices[0].message.content
        print("gpt解析后的简历内容:", response_json)
        return response_json
    except Exception as e:
        print("调用ChatGPT API失败, 错误", e)

    return None

# 调用大模型(文心一言) 解析简历内容，返回json格式简历数据
def wenxin_extract_resume(prompt, resume_content):
    WENXIN_API_KEY = "jgFX7pi2cHpMG6Px0GexcLGy"
    WENXIN_SECRET_KEY = "Mp9lVgeycngPmvLmdrKt3Gy8gSpfWHP7"

    chat_comp = qianfan.ChatCompletion(ak=WENXIN_API_KEY, sk=WENXIN_SECRET_KEY)

    # 调用文心4
    resp = chat_comp.do(model="ERNIE-Bot-4", messages=[{
        "role": "user",
        "content": prompt + resume_content
    }], request_timeout=180000, max_output_tokens=2048)

    # 调用千帆speed12K
    # resp = chat_comp.do(model="ERNIE-Speed-128K", messages=[{
    #     "role": "user",
    #     "content": prompt + resume_content
    # }], request_timeout=180000, max_output_tokens=2048)

    # print(resp)
    if resp.code != 200:
        print("文心一言API接口调用失败, status_code返回:", resp.status_code)
        return None

    resp_body = resp.body
    if resp_body and resp_body.get('result'):
        result = resp_body.get('result')
        json_string_match = re.search(r'```json\n(.*?)```', result, re.DOTALL)
        str_match = re.search(r'\'\'\'(.*?)\'\'\'', result, re.DOTALL)
        if json_string_match:  
            # 提取JSON字符串  
            json_string = json_string_match.group(1)
        elif str_match:
            json_string = str_match.group(1)
        else:
            json_string = ""
            print("文心一言返回数据错误，返回的数据中无json")
    else:  
        json_string = ""
        print("文心一言返回数据错误，无result字段")
  
    print("文心一言解析完后的简历内容:", json_string)
    return json_string

# 调用kimi解析简历内容，返回json_string
def kimi_extract_resume(prompt, resume_content):
    client = OpenAI(
        api_key="sk-y3MvrWd5mQkqVhAD0k4UtGxmOlJy7hQz7kxVmEJYundXsjkK",
        base_url="https://api.moonshot.cn/v1",
    )
 
    completion = client.chat.completions.create(
        model="moonshot-v1-8k",
        messages=[
            {"role": "system", "content": prompt},
            {"role": "user", "content": resume_content}
        ],
        max_tokens=2048
    )
 
    resp_body = completion.choices[0].message
    if resp_body and resp_body.content:
        result = resp_body.content

        # kimi返回的result里面有'```json\n' 和 '\n```', 如'```json\n{\n  "key": "value"\n}\n```' ，需要用正则表达式提取出来 '```json\n' 和 '\n```'  中间的内容
        json_string_match = re.search(r'```json\n(.*?)\n```', result, re.DOTALL)  

        if json_string_match:  
            # 提取JSON字符串  
            json_string = json_string_match.group(1)  
        else:
            json_string = ""
            print("kimi返回数据错误，返回的数据中无json")
    else:
        json_string = ""
        print("kimi返回数据错误，返回的数据中无content字段")

    print("kimi解析完后的简历内容:", json_string)
    return json_string

# 调用火山云雀大模型解析简历内容，返回json_string
def huoshan_extract_resume(prompt, resume_content):
    maas = MaasService('maas-api.ml-platform-cn-beijing.volces.com', 'cn-beijing')
    maas.set_ak("AKLTMDhhOTMzYzZjYjViNDA0ZDllZWViMmI1YjBjMjBhYjM")
    maas.set_sk("WldJM05UUTNNelkzWmpoa05HVXlaR0kyWWpFeVltSTJOelExT1dReFl6WQ==")
    
    req = {
        "model": {
            "name": "Skylark2-pro-32k",
        },
        "parameters": {
            "max_new_tokens": 2048,  # 输出文本的最大tokens限制
        },
        "messages": [{
            "role": ChatRole.USER,
            "content": prompt + resume_content
        }]
    }
    
    resp = maas.chat(req)
    response_json = resp.choice.message.content
    print(response_json)
    return response_json

# 调用腾讯浑元大模型解析简历内容，返回json_string
def tencent_extract_resume(prompt, resume_content):
    # 调用腾讯大模型API，解析简历，输出为json格式
    try:
        # 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
        # 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
        # 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
        cred = credential.Credential("AKIDCHQSPAqmeKrOuFTXNEzfN1ZF0ZxGf2R1", "nS1Ts5KiIueYLwKcqdHqN3qXCsQ8kAkI")
        # 实例化一个http选项，可选的，没有特殊需求可以跳过
        httpProfile = HttpProfile()
        # 推荐使用北极星，相关指引可访问如下链接
        # https://git.woa.com/tencentcloud-internal/tencentcloud-sdk-python#%E5%8C%97%E6%9E%81%E6%98%9F%E4%BD%BF%E7%94%A8%E7%A4%BA%E4%BE%8B
        httpProfile.endpoint = "hunyuan.tencentcloudapi.com"

        # 实例化一个client选项，可选的，没有特殊需求可以跳过
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        # 实例化要请求产品的client对象,clientProfile是可选的
        client = hunyuan_client.HunyuanClient(cred, "ap-beijing", clientProfile)

        # 实例化一个请求对象,每个接口都会对应一个request对象
        req = models.ChatProRequest()
        params = {
            "Messages": [
            {
                "Role": "system",
                "Content": prompt
            },
            {
                "Role": "user",
                "Content": resume_content
            }]
            ,
            "Stream": False
        }
        req.from_json_string(json.dumps(params))

        # 返回的resp是一个ChatProResponse的实例，与请求对象对应
        resp = client.ChatPro(req)
        print(resp)
        for event in resp:
            print(event)
        # 输出json格式的字符串回包
        try:
            response_json = resp.choices[0].message.content
            print("gpt解析后的简历内容:", response_json)
        except Exception as e:
            print("调用混元API失败, 错误", e)

        return response_json
    except TencentCloudSDKException as err:
        print(err)
        return None
    
# 调用通义千问大模型解析简历内容，返回json_string
def qwen_extract_resume(prompt, resume_content):
    print("调用通义千问大模型解析简历内容")
    messages = [{'role': 'system', 'content': prompt},
                {'role': 'user', 'content': resume_content}]
    response = Generation.call("qwen-max",
                               messages=messages,
                               api_key="sk-123669d3642c4d278318ac52763257ba",
                               stream=False,
                               # 将输出设置为"message"格式
                               result_format='message')
    if response.status_code == HTTPStatus.OK:
        try:
            response_json = response.output.choices[0].message.content
            print("千问返回的内容:", response_json)

            json_string_match = re.search(r'```json\n(.*?)\n```', response_json, re.DOTALL)  
            if json_string_match:  
                # 提取JSON字符串  
                json_string = json_string_match.group(1)  
            else:
                json_string = ""
                print("解析返回数据错误，返回的数据中无json")

            print("千问解析后的简历内容:", json_string)
        except Exception as e:
            print("调用通义千问API失败, 错误", e)

    else:
        print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
            response.request_id, response.status_code,
            response.code, response.message
        ))

    return json_string